package com.yjw.apitest.common;

import io.qameta.allure.Allure;
import io.qameta.allure.AllureLifecycle;
import io.qameta.allure.aspects.StepsAspects;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

import java.io.IOException;

import static io.qameta.allure.Allure.getLifecycle;

public class LoggingInterceptor implements Interceptor {

    public Response intercept(Chain chain) throws IOException {
        Response response = null;
        String req = "";
        String reqBody = "";
        String codeMsg = "";
        String respBody = "";
        String title = "";
        Request request = chain.request();
        String method = request.method();
        AllureLifecycle lifecycle =  StepsAspects.getLifecycle();
        try {
            req = "API endpoint: \n  " + method + " " + request.url();
            if ("POST".equals(method) || "PATCH".equals(method) || "PUT".equals(method)) {
                final Request copy = request.newBuilder().build();
                final Buffer buffer = new Buffer();
                copy.body().writeTo(buffer);
                String msg = buffer.readUtf8();
                reqBody = "Request Body: \n  " + msg;
            }
            response = chain.proceed(request);
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            int respCode = response.code();
            boolean isError = respCode != 200 && respCode != 201 && respCode != 204;
            String msg = isError ? "Error code: " : "Resopnse code: ";
            codeMsg = msg + respCode;
            respBody = "Response Body: \n  " + responseBody.string();

            if (isError) {
                title = "error|" + respCode;
            } else {
                title = "success|" + respCode;
            }
            // check lifecycle is not null
            if(lifecycle != null) {
                Allure.addAttachment(title, req + "\n\n" + reqBody + "\n\n" + codeMsg + "\n" + respBody);
            }
            return response;
        } catch (Exception e) {
            // check lifecycle is not null
            if(lifecycle != null) {
                Allure.addAttachment(title, req + "\n\n" + reqBody + "\n\n" + codeMsg + "\n" + respBody);
            }
            return response;
        }
    }
}
